<?php
namespace app\common\logic;
use think\facade\Db;

/**
 * 优惠券逻辑
 */
class Coupon
{
    //发送优惠券 $checktj:是否检测领取条件
    public static function send($user_id,$cpid,$checktj=false,$tr_roomId=0,$setyxq=0,$is_scan=0){
        Db::startTrans();
        $coupon = Db::name('coupon')->where('id',$cpid)->lock(true)->find();
        if(!$coupon){
            Db::commit();
            return ['status'=>0,'msg'=>t('优惠券').'不存在'];
        }
        if($coupon['stock']<=0){
            Db::commit();
            return ['status'=>0,'msg'=>'库存不足'];
        }

        if($checktj){
            $gettj = explode(',',$coupon['gettj']);
            $user = Db::name('users')->where('user_id',$user_id)->find();
            if(!in_array('-1',$gettj) && !in_array($user['rank'],$gettj)){ //不是所有人
                if(count($gettj)==1){
                    $levelname = Db::name('user_level')->where('rank',$gettj[0])->value('level_name');
                    Db::commit();
                    return ['status'=>0,'msg'=>'只有'.$levelname.'才能领取'];
                }
                Db::commit();
                return ['status'=>0,'msg'=>'您没有领取权限'];
            }
        }

        $data = [];
        $data['sid'] = $coupon['sid'];
        $data['user_id'] = $user_id;
        $data['couponid'] = $coupon['id'];
        $data['couponname'] = $coupon['name'];
        $data['money'] = $coupon['money'];
        $data['discount'] = $coupon['discount'];
        $data['minprice'] = $coupon['minprice'];
        if($setyxq){
            //领取后x天有效
            $data['starttime'] = time();
            $data['endtime'] = $data['starttime'] + 86400 * $setyxq;
        }else{
            if($coupon['yxqtype'] == 1){
                //固定有效期
                $yxqtime = explode(' ~ ',$coupon['yxqtime']);
                $data['starttime'] = strtotime($yxqtime[0]);
                $data['endtime'] = strtotime($yxqtime[1]);
            }elseif($coupon['yxqtype'] == 2){
                //领取后x天有效
                $data['starttime'] = time();
                $data['endtime'] = $data['starttime'] + 86400 * $coupon['yxqdate'];
            }
        }

        if($data['endtime'] <= time()){
            Db::commit();
            return ['status'=>0,'msg'=>'优惠券已过期'];
        }
        $data['type'] = $coupon['type'];
        $data['limit_count'] = $coupon['limit_count'];
        $data['limit_perday'] = $coupon['limit_perday'];
        $data['createtime'] = time();

        Db::name('coupon_record')->insert($data);
        Db::name('coupon')->where('id',$coupon['id'])->update(['stock'=>Db::raw('stock-1'),'getnum'=>Db::raw('getnum+1')]);
        Db::commit();
        return ['status'=>1,'msg'=>'发送成功'];
    }
    //支付后送券
    public static function getpaygive($user_id,$type,$money,$orderids=null){
        if(!$money) $money = 0;
        $time = time();
        $whereOr = [];
        $where = [];
        if($type == 'order' && $orderids){
            if(!is_array($orderids)){
                $orderids = [$orderids];
            }
            $proids = Db::name('order_goods')->where('order_id','in',$orderids)->column('goods_id');
            foreach($proids as $proid){
                $whereOr[] = "find_in_set('{$proid}',buyproids)";
            }
        }
        $whereOr = implode(' or ',$whereOr);
        if($whereOr){
            $whereOr = "(buyprogive=1 and ({$whereOr}))";
        }else{
            $whereOr = '(1=0)';
        }

        $couponlist = Db::name('coupon')->where($where)->where("unix_timestamp(starttime)<={$time} and unix_timestamp(endtime)>={$time} and stock>0")
            ->where("(paygive=1 and paygive_minprice<={$money} and paygive_maxprice>={$money} and find_in_set('{$type}',paygive_scene)) or $whereOr")
            ->order('sort desc,id desc')->select()->toArray();
        //var_dump(Db::getlastsql());
        foreach($couponlist as $k=>$coupon){
            $havegetnum = Db::name('coupon_record')->where('user_id',$user_id)->where('couponid',$coupon['id'])->count();
            if($havegetnum >= $coupon['perlimit']) unset($couponlist[$k]);
        }
        if(!$couponlist) return false;

        foreach($couponlist as $k=>$coupon){
            $thisnum = 0;
            if($coupon['paygive']==1 && $coupon['paygive_minprice'] <= $money && $coupon['paygive_maxprice'] >= $money && in_array($type,explode(',',$coupon['paygive_scene']))){
                $thisnum++;
            }
            if($type == 'order' && $orderids && $coupon['buyprogive'] == 1){
                $coupon['buyproids'] = explode(',',$coupon['buyproids']);
                $coupon['buypro_give_num'] = explode(',',$coupon['buypro_give_num']);
                foreach($coupon['buyproids'] as $k2 => $proid) {
                    if(in_array($proid, $proids) && $coupon['buypro_give_num'][$k2] > 0) {
                        $thisnum += $coupon['buypro_give_num'][$k2];
                    }
                }
            }
            $couponlist[$k]['givenum'] = $thisnum;
            if($coupon['sid']>0){
                $bname = Db::name('suppliers')->where('id',$coupon['sid'])->value('name');
                $couponlist[$k]['bname'] = $bname??'';
            }else{
                $couponlist[$k]['bname'] = '平台';
            }
            $couponlist[$k]['type_txt'] = self::getCouponTypeTxt($coupon['type']);
        }

        return $couponlist;
    }

    public static function getCouponTypeTxt($type=''){
        $couponTypes = [
            '1'=>'代金券',
            '2'=>'折扣券',
        ];
        if($type && isset($couponTypes[$type])){
            return $couponTypes[$type];
        }
        return $type;
    }
    //使用优惠券

    /**
     * @param $aid
     * @param $coupon_record_id
     * @param $usecoupon_type 1付款后，2确认收货,hexiao
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function useCoupon($coupon_record_id,$usecoupon_type=1,$proids=[]){
        //该优惠券是不是赠送的
        $crecord = Db::name('coupon_record')->where('id',$coupon_record_id)->find();
        if($crecord['from_mid']){
            //是不是满足条件
            $coupon = Db::name('coupon')->where('id',$crecord['couponid'])->find();
        }
    }

    public static function getUserCouponList($user_id,$sid,$type='all',$price=0,$proids='',$cids=''){
        $user = Db::name('users')->where('user_id',$user_id)->find();
        $couponList = Db::name('coupon_record')->where('user_id',$user_id)->where('type','in','1,2')->where('status',0)
            ->whereRaw("sid=-1 or sid=".$sid." or (sid=0 and (canused_bids='all' or find_in_set(".$sid.",canused_bids) ))")
            ->where('starttime','<=',time())->where('endtime','>',time())
            ->order('id desc')->select()->toArray();
        if(!$couponList) $couponList = [];
        foreach($couponList as $k=>$v){
            $couponinfo = Db::name('coupon')->where('id',$v['couponid'])->find();
            $couponinfo['isgive'] = 0;


            //0全场通用,1指定类目,2指定商品
            if(!in_array($couponinfo['fwtype'],[0,1,2])){
                continue;
            }
            $usetj = explode(',',$couponinfo['gettj']);
            if(!in_array('-1',$usetj) && !in_array($user['level'],$usetj) ){
                continue;
            }

            $v['thistotalprice'] = $price;
            $v['couponmoney'] = $v['money'];
            if($couponinfo['fwtype']==2){//指定商品可用
                $productids = explode(',',$couponinfo['productids']);
                if(!array_intersect($proids,$productids)){
                    continue;
                }
                $v['productids'] = $productids;
                $thistotalprice = 0;

                if($thistotalprice < $v['minprice']){
                    continue;
                }
                $v['thistotalprice'] = $thistotalprice;
                $v['couponmoney'] = min($thistotalprice,$v['money']);//可抵扣金额
            }
            if($couponinfo['fwtype']==1){//指定类目可用
                if(!$couponinfo['categoryids']) continue;
                $categoryids = explode(',',$couponinfo['categoryids']);
                $clist = Db::name('shop_category')->where('pid','in',$categoryids)->select()->toArray();
                foreach($clist as $kc=>$vc){
                    $categoryids[] = $vc['id'];
                    $cate2 = Db::name('shop_category')->where('pid',$vc['id'])->find();
                    if($cate2) $categoryids[] = $cate2['id'];
                }
                if(!array_intersect($cids,$categoryids)){
                    continue;
                }
                $thistotalprice = 0;

                if($thistotalprice < $v['minprice']){
                    continue;
                }
                $v['thistotalprice'] = $thistotalprice;
                $v['couponmoney'] = min($thistotalprice,$v['money']);//可抵扣金额
            }
            if($v['sid'] > 0){
                $binfo = Db::name('suppliers')->where('id',$v['sid'])->find();
                $v['sname'] = $binfo['same'];
            }
            $newcouponlist[] = $v;
        }
        $couponList = $newcouponlist??[];
        return ['status'=>1,'couponList'=>$couponList];
    }
}